package com.seleniti.enpareja.controller.ui.view;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.Objects;
import java.util.Set;

import org.ioc.commons.flowcontrol.actioncontroller.ActionController;
import org.ioc.commons.flowcontrol.actioncontroller.ActionHandler;
import org.ioc.commons.flowcontrol.common.impl.ReceiverAdapter;
import org.ioc.commons.flowcontrol.eventbus.EventBus;
import org.ioc.commons.flowcontrol.logincontroller.IsLoggedUserInfoConsumer;
import org.ioc.commons.flowcontrol.messageboxfactory.MessageBoxFactory.PromptResponse;
import org.ioc.commons.flowcontrol.notificator.NotificationManager;
import org.ioc.commons.flowcontrol.notificator.NotificationManager.Priority;
import org.ioc.commons.flowcontrol.notificator.Notificator.NotificationPermission;
import org.ioc.commons.flowcontrol.operationmanager.OperationManager;
import org.ioc.commons.flowcontrol.operationmanager.impl.OperationHandlerFactory;
import org.ioc.commons.flowcontrol.taskcontroller.Task;
import org.ioc.commons.flowcontrol.taskcontroller.TaskController.SchedulerType;
import org.ioc.commons.flowcontrol.taskcontroller.TaskHandler;
import org.ioc.commons.model.globaldata.GlobalDataController.Consumer;
import org.ioc.commons.model.globaldata.IsGlobalDataConsumer;
import org.ioc.commons.utils.Format;
import org.ioc.commons.utils.FormatterLogger;
import org.ioc.commons.utils.datetime.DateUtils;

import com.seleniti.enpareja.controller.common.GlobalData;
import com.seleniti.enpareja.controller.common.domain.LoggedUserInfo;
import com.seleniti.enpareja.controller.common.domain.UserAgent;
import com.seleniti.enpareja.controller.control.factory.ClientFactory.NotificationIcons;
import com.seleniti.enpareja.controller.control.place.EnParejaPlace;
import com.seleniti.enpareja.controller.model.integration.database.domain.Couple;
import com.seleniti.enpareja.controller.model.integration.database.domain.CoupleType;
import com.seleniti.enpareja.controller.model.integration.database.domain.HomeTask;
import com.seleniti.enpareja.controller.model.integration.database.domain.HomeTask.MadeBy;
import com.seleniti.enpareja.controller.model.integration.database.domain.NotificationType;
import com.seleniti.enpareja.controller.ui.base.EnParejaViewBasePresenter;
import com.seleniti.enpareja.controller.ui.main.AppShell;
import com.seleniti.enpareja.controller.ui.view.HomeTasksView.Action;
import com.seleniti.enpareja.controller.ui.view.HomeTasksView.ActionMode;
import com.seleniti.enpareja.controller.ui.view.HomeTasksView.Board;
import com.seleniti.enpareja.controller.ui.view.HomeTasksView.Event;
import com.seleniti.enpareja.controller.ui.view.HomeTasksView.Operation;

/**
 * Presenter for the Login view
 * 
 * @author Jesús Lunar Pérez
 * 
 */
public class HomeTasksViewPresenter extends
		EnParejaViewBasePresenter<HomeTasksView, HomeTasksView.Event, HomeTasksView.Operation, HomeTasksView.Action>
		implements HomeTasksView.Presenter, IsLoggedUserInfoConsumer<LoggedUserInfo>, IsGlobalDataConsumer<GlobalData> {

	private static final FormatterLogger logger = FormatterLogger.getLogger(HomeTasksViewPresenter.class);

	protected static final int LIST_SIZE_LIMIT_TO_SHOW_LOAD_BASICS = 5;

	private static final String[] REQUIRED_PROPERTIES = { "homeTasks", "member1", "member2", "pendingHomeTasks" };

	private Consumer<GlobalData> consumer;
	protected boolean refreshedAtLeastOnce;

	private HomeTask suggestScheduleOnRefresh;

	private TaskHandler hideScheduleSuggestionTaskHandler;

	public HomeTasksViewPresenter(HomeTasksView display, EventBus<Event> eventbus,
			OperationManager<Operation> operationManager, ActionController<Action> actionController) {
		super(display, eventbus, operationManager, actionController);
		this.consumer = this.globalDataController.registerGlobalDataConsumer(this);
	}

	@Override
	public void onInitDisplay() {
		super.onInitDisplay();
		display.setActionMode(ActionMode.SWITCH_LIST);
		shell.loadBasicsButtonText().setText("Tareas básicas");

		this.consumer.requires(GlobalData.UserAgent);
	}

	@Override
	protected void bindComponents() {
		super.bindComponents();
		operationManager.bindOperationsRunning(OperationHandlerFactory.<Operation> forLoaders(display));
		operationManager.bindOperationsRunning(OperationHandlerFactory.<Operation> forLoaders(shell.globalLoader()));

		shell.actionController().bindAction(AppShell.Action.DeleteNow, new ActionHandler<AppShell.Action>() {

			@Override
			public void handleAction(Object sender, com.seleniti.enpareja.controller.ui.main.AppShell.Action action,
					Object... params) {
				deleteSelected();
			}
		});

		shell.actionController().bindAction(AppShell.Action.LoadBasics, new ActionHandler<AppShell.Action>() {

			@Override
			public void handleAction(Object sender, com.seleniti.enpareja.controller.ui.main.AppShell.Action action,
					Object... params) {
				display.showBasics();
			}
		});
	}

	protected void deleteSelected() {
		if (display.getActionMode() == ActionMode.DELETE_ELEMENT) {
			Couple couple = display.couple().getValue();
			Set<HomeTask> selection = display.getSelection();

			if (couple.getHomeTasks() != null) {
				couple.getHomeTasks().removeAll(selection);
				saveCouple(Operation.Saving, operationManager, true);
				display.setActionMode(ActionMode.SWITCH_LIST);
			}
		}

	}

	@Override
	public void onActive() {
		super.onActive();

		logger.info("Activating Home tasks");

		shell.refreshButtonVisibility().setVisible(true);
		display.boardShown().setValue(Board.TASKS_LIST);

		this.loginController.requiresLoggedUserInfoIfDisplayActive(this);
		this.consumer.ensureRequirements();
	}

	@Override
	public void onDeactive() {
		super.onDeactive();

		shell.loadBasicsButtonVisibility().setVisible(false);
	}

	private void refreshLoggedUserInfo() {
		LoggedUserInfo lui = this.loginController.getLoggedUserInfo();

		display.setEnabled(lui != null && lui.getCoupleName() != null && !lui.getCoupleName().isEmpty());
		shell.nonAssociatedPanelVisibility()
				.setVisible(
						lui != null
								&& lui.isLogged()
								&& (lui.getCoupleName() == null || lui.getCoupleName().isEmpty() || lui.getCoupleType() == CoupleType.TESTING_MODE_COUPLE));

		shell.firstStepsVisibility().setVisible(
				shell.nonAssociatedPanelVisibility().isVisible()
						&& lui.getCoupleType() != CoupleType.TESTING_MODE_COUPLE);
		shell.nonAssociatedButtonVisibility().setVisible(!shell.firstStepsVisibility().isVisible());
		display.coupleType().setValue(lui != null ? lui.getCoupleType() : null);
	}

	@Override
	public void onRequiredGlobalDataReady() {
		showGoBackButtonIfRequired();
	}

	@Override
	public void onRequiredGlobalDataNotReadyYet() {
		/*
		 * Nothing to do
		 */
	}

	@Override
	public void onRequiredGlobalDataUpdated(GlobalData globalDataUpdated) {
		showGoBackButtonIfRequired();
	}

	@Override
	protected void refreshData() {
		super.refreshCouple(new ReceiverAdapter<Couple>() {

			@Override
			public void success(Couple result) {
				display.homeTasksList().clear();
				display.pendingCounter().setValue(result != null ? result.getPendingHomeTasks() : null);
				if (result != null && result.getHomeTasks() != null) {
					if (Boolean.TRUE.equals(display.onlyPendingFilter().getValue())) {
						for (HomeTask element : result.getHomeTasks()) {
							if (element.getLastTime() == null) {
								display.homeTasksList().add(element);
							}
						}
					} else {
						display.homeTasksList().addAll(result.getHomeTasks());
					}
				}
				HomeTasksViewPresenter.this.refreshedAtLeastOnce = true;
				refreshMemberText();
				tryToShowBasicsList();
				tryToShowSchedulingSuggestion();
			}
		}, Operation.GettingData, operationManager, REQUIRED_PROPERTIES);

	}

	protected void tryToShowSchedulingSuggestion() {

		// TODO: JLP.- ¡¡¡¡ DESACTIVADO PARA LA SIGUIENTE SUBIDA !!!
		if (1 == 1) {
			return;
		}

		if (this.suggestScheduleOnRefresh != null && !display.scheduleSuggestionVisibility().isVisible()) {

			display.scheduleSuggestionText().setText(
					Format.substitute("Planificar {0}", this.suggestScheduleOnRefresh.getText()));
			display.scheduleSuggestionVisibility().setVisible(true);
			display.scheduleSuggestionEnabled().setEnabled(true);
			this.hideScheduleSuggestionTaskHandler = this.taskController.scheduleDelayed(5000, new Task() {

				@Override
				public void run() {
					hideScheduleSuggestion(true);
				}
			});

		}
	}

	@Override
	public void onHideScheduleSuggestion() {
		hideScheduleSuggestion(true);
	}

	protected void hideScheduleSuggestion(boolean clearSuggestedElement) {
		display.scheduleSuggestionEnabled().setEnabled(false);
		display.scheduleSuggestionVisibility().setVisible(false);
		if (this.hideScheduleSuggestionTaskHandler != null) {
			this.hideScheduleSuggestionTaskHandler.cancel();
			this.hideScheduleSuggestionTaskHandler = null;
			if (clearSuggestedElement) {
				suggestScheduleOnRefresh = null;
			}
		}
	}

	@SuppressWarnings("deprecation")
	@Override
	public void onScheduleSuggestion() {
		hideScheduleSuggestion(false);
		Date now = new Date();
		Date after10minutes = new Date();
		after10minutes.setMinutes(after10minutes.getMinutes() + 10);

		display.scheduleDate().setValue(now);
		display.scheduleTime().setValue(after10minutes);
		display.boardShown().setValue(Board.SCHEDULE_FORM);
	}

	@Override
	public void onLoggedUserInfoDataReady() {
		LoggedUserInfo loggedUserInfo = this.loginController.getLoggedUserInfo();

		if (!Objects.equals(loggedUserInfo, display.loggedUserInfo().getValue())) {

			this.display.loggedUserInfo().setValue(loggedUserInfo);
			refreshData();
			refreshLoggedUserInfo();
		}
	}

	@Override
	public void onLoggedUserInfoDataUpdated(LoggedUserInfo loggedUserInfo) {
		refreshLoggedUserInfo();
	}

	@Override
	public void onLoggedUserInfoNotReadyYet() {
		/*
		 * Nothing to do
		 */
	}

	@Override
	public void onSwitchElementFromList(HomeTask value) {
		switchElementFromList(value, true);
	}

	protected void switchElementFromList(HomeTask value, boolean trySave) {

		boolean pending = value.getLastTime() != null;

//		if (!ensureCouple(pending ? "Marcar una tarea como pendiente" : "Marcar una tarea como hecha",
//				Operation.GettingData, operationManager, REQUIRED_PROPERTIES)) {
//			return;
//		}

		if (pending) {
			logger.info("Marcando como no hecho");
			value.setLastTime(null);
			value.setMadeBy(null);

			LoggedUserInfo lastLui = display.loggedUserInfo().getValue();

			String extraInfo = (lastLui != null && lastLui.getCoupleMemberNo() > 0) ? Format.substitute(
					"{member{0}} marcó {1} como pendiente", lastLui.getCoupleMemberNo(), value.getText()) : Format
					.substitute("{0} está ahora pendiente", value.getText());
			if (trySave) {
				this.suggestScheduleOnRefresh = value;
				saveCouple(Operation.Saving, operationManager, true, NotificationType.HOME_TASKS_CHANGED, extraInfo);
			}
		} else {
			logger.info("Marcando como hecho");
			display.lastTime().setValue(new Date());
			display.showTaskDoneSettings(value, false);
		}
	}

	@Override
	public void onAddNewElement() {
		messageBoxFactory.prompt("Nueva tarea", "Escribe el nombre de la tarea que quieres añadir", "",
				new PromptResponse() {

					@Override
					public void onUserResponse(boolean userResponse, String response) {
						if (userResponse && response != null && !response.isEmpty()) {
							String text = Format.capitalize(response);

							addNewElement(text, true);
						}
					}
				});
	}

	@Override
	public void onAddSelectedBasicElements() {
		logger.info("Adding {0} selected basic elements", display.selectedBasicTasks().size());

		if (!display.selectedBasicTasks().isEmpty()) {
			for (String basicProduct : display.selectedBasicTasks()) {
				addNewElement(basicProduct, false);
			}

			saveCouple(Operation.Saving, operationManager, true);
		}

		display.boardShown().setValue(Board.TASKS_LIST);
		tryToShowBasicsList();
	}

	@Override
	public void onCancelAddingSelectedBasicElements() {
		display.selectedBasicTasks().clear();
		display.boardShown().setValue(Board.TASKS_LIST);
		tryToShowBasicsList();
	}

	@Override
	public void onActionModeChanged() {
		ActionMode mode = display.getActionMode();

		logger.info("Action mode changed: {0}", mode);

		switch (mode) {
		case DELETE_ELEMENT:
			this.shell.deleteButtonVisibility().setVisible(true);
			this.shell.loadBasicsButtonVisibility().setVisible(false);
			break;
		default:
			this.shell.deleteButtonVisibility().setVisible(false);
			tryToShowBasicsList();
		}

	}

	@Override
	public void onSelectionChanged() {
		ActionMode mode = display.getActionMode();

		logger.info("Selection changed on mode {0}", mode);

		if (mode == ActionMode.MODIFY_ELEMENT) {
			Set<HomeTask> selection = display.getSelection();

			if (!selection.isEmpty()) {
				HomeTask single = selection.iterator().next();

				display.modifyElement(single);
			}
		}

	}

	@Override
	public void onModifyElement(final HomeTask element) {
		messageBoxFactory.prompt("Cambiar", "Escribe el nuevo nombre de la tarea", element.getText(),
				new PromptResponse() {

					@Override
					public void onUserResponse(boolean userResponse, String response) {
						if (userResponse && response != null && !response.isEmpty()) {

							element.setText(Format.capitalize(response));

							if (element.getLastTime() != null) {
								display.lastTime().setValue(element.getLastTime());
								display.showTaskDoneSettings(element, true);
							} else {
								display.lastTime().setValue(new Date());
								saveCouple(Operation.Saving, operationManager, true);
							}

							display.setActionMode(ActionMode.SWITCH_LIST);
						}

					}
				});
	}

	private void refreshMemberText() {
		Couple couple = display.couple().getValue();
		logger.info("Refreshing member text... couple={0}", couple);
		if (couple != null) {
			String member1 = couple.getMember1() != null ? couple.getMember1().getNickName() : null;
			String member2 = couple.getMember2() != null ? couple.getMember2().getNickName() : null;

			display.member1().setText(member1 != null && !member1.isEmpty() ? member1 : "-- miembro 1 --");
			display.member2().setText(member2 != null && !member2.isEmpty() ? member2 : "-- miembro 2 --");

			logger.info("Member 1: {0} Member 2: {1}", member1, member2);
		} else {
			logger.info("Not refreshed. No logged user info");
		}
	}

	@Override
	public void onMarkSelectedAsMadeByMember1() {
		MadeBy madeBy = MadeBy.MEMBER_1;
		markSelectedAsMadeBy(madeBy);
	}

	@Override
	public void onMarkSelectedAsMadeByMember2() {
		MadeBy madeBy = MadeBy.MEMBER_2;
		markSelectedAsMadeBy(madeBy);
	}

	@Override
	public void onMarkSelectedAsMadeByBoth() {
		MadeBy madeBy = MadeBy.BOTH;
		markSelectedAsMadeBy(madeBy);
	}

	protected void markSelectedAsMadeBy(MadeBy madeBy) {
		HomeTask settingsForThis = this.display.getSettingsForThis();
		logger.info("Marking selected as made by {0}. Selected={1}", madeBy, settingsForThis);

		display.hideTaskDoneSettings();

		if (settingsForThis != null) {
			settingsForThis.setMadeBy(madeBy);
			Date lastTime = display.lastTime().getValue();
			settingsForThis.setLastTime(lastTime);

			LoggedUserInfo lastLui = display.loggedUserInfo().getValue();

			String extraInfo = (lastLui != null && lastLui.getCoupleMemberNo() > 0) ?

			(lastLui.getCoupleMemberNo() == 1 && madeBy == MadeBy.MEMBER_1)
					|| (lastLui.getCoupleMemberNo() == 2 && madeBy == MadeBy.MEMBER_2) ?

			Format.substitute("{member{0}} ha terminado de {1}", lastLui.getCoupleMemberNo(), settingsForThis.getText())
					: Format.substitute("{member{0}} ha marcado {1} como {2}", lastLui.getCoupleMemberNo(),
							settingsForThis.getText(), madeBy == MadeBy.BOTH ? "hecho por ambos"
									: madeBy == MadeBy.MEMBER_1 ? "hecho por {member1}" : "hecho por {member2}")
					: Format.substitute("Se ha terminado de {0}", settingsForThis.getText());

			saveCouple(Operation.Saving, operationManager, true, NotificationType.HOME_TASKS_CHANGED, extraInfo);
		}
	}

	@Override
	public void onDoneOrPendingButtonToggled() {
		this.refreshData();
	}

	@Override
	public void onModifyButtonToggled(boolean enabled) {
		display.setActionMode(enabled ? ActionMode.MODIFY_ELEMENT : ActionMode.SWITCH_LIST);
	}

	@Override
	public void onRefreshData() {
		refreshData();
	}

	private final static String[] BASIC_PRODUCTS = { "Aspirar", "Barrer", "Limpiar cristales", "Fregar suelo",
			"Lavar los platos", "Hacer almuerzo", "Hacer la cena", "Hacer la cama", "Limpiar el polvo",
			"Limpiar cocina", "Planchar", "Poner lavadora", "Tender", "Sacar basura", "Poner lavavajillas", };

	@Override
	public void onShowBasics() {
		loadAndShowBasics();
	}

	protected void loadAndShowBasics() {
		Couple couple = display.couple().getValue();

		if (couple != null) {
			if (display.basicTasks().isEmpty()) {

				display.basicTasks().addAll(Arrays.asList(BASIC_PRODUCTS));

				Collections.sort(display.basicTasks(), new Comparator<String>() {

					@Override
					public int compare(String o1, String o2) {
						return o1.compareTo(o2);
					}
				});
			}

			display.selectedBasicTasks().clear();
			display.boardShown().setValue(Board.BASIC_TASKS_LIST);
			shell.loadBasicsButtonVisibility().setVisible(false);
		} else {
			logger.warn("Required couple for loading basic products not found");
			messageBoxFactory.alert("Algo no va bien", "Parece que no puedes cargar la lista de tareas básicas.");
		}
	}

	protected void addNewElement(String text, boolean save) {
		/**
		 * In case user is adding a element which previously exists, just modify
		 * it.
		 */
		boolean exists = false;
		Couple couple = display.couple().getValue();

		for (HomeTask old : couple.getHomeTasks()) {
			if (text.equals(old.getText()) && old.getLastTime() != null) {
				switchElementFromList(old, save);
				exists = true;
				break;
			}
		}

		if (!exists) {
			HomeTask sle = new HomeTask();

			sle.setText(text);
			sle.setCouple(couple);

			if (couple.getHomeTasks() == null) {
				couple.setHomeTasks(new ArrayList<HomeTask>());
			}

			couple.getHomeTasks().add(sle);
		}

		if (save) {
			saveCouple(Operation.Saving, operationManager, true);
		}
	}

	protected void tryToShowBasicsList() {
		if (HomeTasksViewPresenter.this.refreshedAtLeastOnce
				&& !Boolean.TRUE.equals(display.onlyPendingFilter().getValue())) {
			shell.loadBasicsButtonVisibility().setVisible(
					!display.operationManager().isBusy()
							&& display.homeTasksList().size() < LIST_SIZE_LIMIT_TO_SHOW_LOAD_BASICS);
		}
	}

	@Override
	public void onScheduleSuggestedForMember1() {
		scheduleTaskForMember(MadeBy.MEMBER_1);
	}

	@Override
	public void onScheduleSuggestedForMember2() {
		scheduleTaskForMember(MadeBy.MEMBER_2);
	}

	@Override
	public void onScheduleSuggestedForBoth() {
		scheduleTaskForMember(MadeBy.BOTH);
	}

	protected void scheduleTaskForMember(MadeBy member) {
		Date date = display.scheduleDate().getValue();
		Date time = display.scheduleTime().getValue();
		LoggedUserInfo lui = this.loginController.getLoggedUserInfo();

		logger.info("Scheduling task for member {0} at date {1} time {2}", member, date, time);

		if (date == null) {
			messageBoxFactory.alert("Planificar tarea", "Elige una fecha válida");
		} else if (time == null) {
			messageBoxFactory.alert("Planificar tarea", "Elige una hora válida");
		} else if (lui == null) {
			messageBoxFactory.alert("Planificar tarea",
					"No se puede planificar. Parece que no has iniciado sesión como usuario.");
		} else if (suggestScheduleOnRefresh == null) {
			logger.error("Unable to schedule notification. Suggested task to schedule not found.");
		} else {
			final Date datetime = DateUtils.joinDateAndTime(date, time);
			final Date now = new Date();

			if (datetime.before(now)) {
				logger.info("Trying to schedule task in bad time: {0} < {1} (now)", datetime, now);
				messageBoxFactory.alert("Planificar tarea", "No se puede planificar una tarea a una hora ya pasada.");
				return;
			}

			final String notificationMessage = Format.substitute("Es hora de {0}", suggestScheduleOnRefresh.getText());
			final NotificationType notifcationType = NotificationType.MAKE_HOMETASK;
			if (member == MadeBy.BOTH || (lui.getCoupleMemberNo() == 1 && member == MadeBy.MEMBER_1)
					|| (lui.getCoupleMemberNo() == 2 && member == MadeBy.MEMBER_2)) {

				if (notificator != null) {

					logger.info("Notifications available");

					if (notificator.requiresRequestSystemPermission()
							&& notificator.getCurrentSystemNotificationPermission() != NotificationPermission.GRANTED) {
						logger.info("User permission required");
						notificator.requestPermission();
					}

					/**
					 * Saving notification as scheduled before scheduling. This
					 * will allow us to re-schedule them after rebooting device.
					 */
					serviceManager
							.serviceFactory()
							.notificationService()
							.storeLoggedUserScheduledNotification(notifcationType, notificationMessage, datetime,
									suggestScheduleOnRefresh.getHomeTaskId())
							.performing(Operation.Scheduling, operationManager).caller(this)
							.to(new ReceiverAdapter<String>() {

								@Override
								public void success(final String notificationId) {
									long notifDatetimeMillis = datetime.getTime() - now.getTime();

									logger.info("Delaying task {0} millis", notifDatetimeMillis);

									logger.info("Scheduling task for logged user at {0} (in {1} millis)", datetime,
											notifDatetimeMillis);

									SchedulerType schedulerType = null;
									if (taskController.isSchedulerTypeSupported(SchedulerType.SYSTEM_SCHEDULER)) {
										schedulerType = SchedulerType.SYSTEM_SCHEDULER;
									} else {
										schedulerType = SchedulerType.APPLICATION_SCHEDULER;
									}

									taskController.scheduleDelayed(schedulerType, notifDatetimeMillis, new Task() {

										@Override
										public void run() {
											/*
											 * Notification has been read by the
											 * user
											 */
											serviceManager.serviceFactory().notificationService().read(notificationId)
													.caller(HomeTasksViewPresenter.this);

											NotificationManager<NotificationIcons> notificationManager = notificator
													.notify(notificationMessage.hashCode(), "Tarea programada",
															notificationMessage)
													.icon(NotificationIcons.CALENDAR_ICON)
													.priority(
															notifcationType.isHighPriority() ? Priority.MAX_PRIORITY
																	: Priority.NORMAL_PRIORITY)
													.onclick(placeController, EnParejaPlace.HomeTasks);
											if (notificator.areActionsOnNotificationsSupported()
													&& notifcationType.isSchedulable()) {
												notificationManager.addAction(actionController, "Hecho",
														Action.TaskDone).addAction(actionController, "Postponer",
														Action.SnoozeTask);
											}

											if (!notificationManager.isShownAutomatically()) {
												notificationManager.show();
											}
										}
									});
								}
							});

				} else {
					logger.info("Notifications unavailable");
				}

				UserAgent ua = (UserAgent) globalDataController.getGlobalDataValue(GlobalData.UserAgent);

				if (ua != UserAgent.ANDROID_APP) {
					logger.info("Notificating mobile devices too...");
					/*
					 * We notify on logged user mobile too
					 */
					serviceManager.serviceFactory().notificationService()
							.notifyLoggedUser(notifcationType, notificationMessage, datetime);
				}
			} else {
				logger.info("Notificating user couple...");

				serviceManager.serviceFactory().notificationService()
						.notifyLoggedUserCouple(notifcationType, notificationMessage, datetime);
			}

			display.hideScheduleForm();
		}

		suggestScheduleOnRefresh = null;
	}

	@Override
	public void onHideScheduleForm() {
		display.boardShown().setValue(Board.TASKS_LIST);
	}
}
